//AES 对称加密
import CryptoJS from "crypto-js"
import { useCryptoStore } from "@/store/useCryptoStore"

/**
 *  对传入的数据进行加密
 * @param value {{string}} 要加密的数据
 * @returns {{string}}  加密后的数据
 */
const encrypt = (value: string): string => {
  let { publicKey, iv } = useCryptoStore()
  publicKey = CryptoJS.enc.Utf8.parse(publicKey)
  iv = CryptoJS.enc.Utf8.parse(iv)

  const srcs = CryptoJS.enc.Utf8.parse(value)
  const encrypted = CryptoJS.AES.encrypt(srcs, publicKey, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.ciphertext.toString().toUpperCase()
}

/**
 *  对加密后的数据进行解密
 * @param value {{string}} 要解密的数据
 * @returns {{string}}  解密后的数据
 */
const decrypt = (value: string): string => {
  let { publicKey, iv } = useCryptoStore()
  publicKey = CryptoJS.enc.Utf8.parse(publicKey)
  iv = CryptoJS.enc.Utf8.parse(iv)
  const encryptedHexStr = CryptoJS.enc.Hex.parse(value)
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  const decrypt = CryptoJS.AES.decrypt(srcs, publicKey, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

/**
 * DES加密方法
 * @param value {{string}} 要加密的数据
 * @returns {{string}}  加密后的数据
 */
const desEncrypt = (value: string): string => {
  let { publicKey, iv } = useCryptoStore()
  publicKey = CryptoJS.enc.Utf8.parse(publicKey)
  iv = CryptoJS.enc.Utf8.parse(iv)
  const encrypted = CryptoJS.DES.encrypt(value, publicKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.toString()
}

/**
 * DES解密方法
 * @param value {{string}} 要解密的数据
 * @returns {{string}}  解密后的数据
 */
const desDecrypt = (ciphertext: string): string => {
  let { publicKey, iv } = useCryptoStore()
  publicKey = CryptoJS.enc.Utf8.parse(publicKey)
  iv = CryptoJS.enc.Utf8.parse(iv)
  if (ciphertext === "" || ciphertext === null || ciphertext === undefined) return ""

  if (typeof ciphertext != "string") ciphertext = ciphertext.toString()

  const decrypted = CryptoJS.DES.decrypt(
    {
      ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
    },
    publicKey,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    },
  )
  return decrypted.toString(CryptoJS.enc.Utf8)
}

export { encrypt, decrypt, desEncrypt, desDecrypt }
